<?php
namespace Models;

require_once('Album.php');
require_once('\Common\DBTables.php');

class AlbumCatalog
{	
	/**
	 * Hämtar en array av album
	 * @return $users UserArray
	 */
	public function getAlbums(\Models\Database $db, $userId = "", $albumYear = "")
	{
		$dbt = new \Common\DBTables();
		
		$sql = "SELECT ".
		$dbt->albumIdField.",".
		$dbt->userIdField.",".
		$dbt->albumTitleField.",".
		$dbt->albumYearField.",".
		$dbt->albumDescriptionField." 
		FROM ".$dbt->albumTable." ";
		
		if($userId != "" || $albumYear != "")
		{
			// Specifik användare och specifikt år
			if($userId != "" && $albumYear != "")
				$sql .= "WHERE ".$dbt->userIdField."=".$userId." AND ".$dbt->albumYearField."=".$albumYear;
			// Specifik användare
			else if($userId != "" && $albumYear == "")
				$sql .= "WHERE ".$dbt->userIdField."=".$userId;
			// Specifikt år
			else if($userId == "" && $albumYear != "")
				$sql .= "WHERE ".$dbt->albumYearField."=".$albumYear;
		}
			
		
		$statement = $db->Select($sql);
		
		// Bind resultat innan vi anropar fetch()
		if ($statement->bind_result($dbt->albumIdField, $dbt->userIdField, $dbt->albumTitleField, $dbt->albumYearField, $dbt->albumDescriptionField) == FALSE)
			throw new \Exception($this->mysqli->error);

	    $albums = new \Models\AlbumArray();
		
	    while ($statement->fetch())
	    {
	        $album = new \Models\Album($dbt->albumIdField, $dbt->userIdField, $dbt->albumTitleField, $dbt->albumYearField, $dbt->albumDescriptionField);
			$albums->add($album);
	    }
		
		$statement->close();
		
		return $albums;
	}
	
	/**
	 * Hämtar ett album
	 * @return $user User
	 */
	public static function getAlbum(\Models\Database $db, $albumId)
	{
		$dbt = new \Common\DBTables();
		
		$sql = "SELECT ".
		$dbt->albumIdField.",".
		$dbt->userIdField.",".
		$dbt->albumTitleField.",".
		$dbt->albumYearField.",".
		$dbt->albumDescriptionField." 
		FROM ".$dbt->albumTable."
		WHERE ".$dbt->albumIdField."='".$albumId."'";
		
		$statement = $db->Select($sql);
		
		// Bind resultat innan vi anropar fetch()
		if ($statement->bind_result($dbt->albumIdField, $dbt->userIdField, $dbt->albumTitleField, $dbt->albumYearField, $dbt->albumDescriptionField) == FALSE)
			throw new \Exception($this->mysqli->error);
		
	    if($statement->fetch())
	        $album = new \Models\Album($dbt->albumIdField, $dbt->userIdField, $dbt->albumTitleField, $dbt->albumYearField, $dbt->albumDescriptionField);
		else
			return null;
		
		$statement->close();
		
		return $album;
	}
}

?>